/**
 * kl yy-ds @2021
 */
package com.cxps.server.user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cxps.cloud.enums.DataStatus;
import com.cxps.cloud.utils.DateUtil;
import com.cxps.cloud.utils.IdUtils;
import com.cxps.cloud.utils.StringConvertUtil;
import com.cxps.server.user.domain.*;
import com.cxps.server.user.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 用户业务逻辑层
 *
 * @author YouCai.Liu
 * @since 2021/10/8 21:21
 * ...
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 查询用户列表数据
     *
     * @param query
     * @return
     */
    public Page getUserList(UserQuery query) {

        // 预先的校验
        if (null == query) {
            throw new IllegalArgumentException("query不能为空");
        }

        // MP分页对象
        Page<UserEntity> page = new Page<>(query.getCurrent(), query.getSize());

        // 设置排序字段
        if (StringUtils.isBlank(query.getSortOrder())) {
            // 按照 update_time 倒序排，如果一样在按照 id 正序排
            page.addOrder(OrderItem.desc("update_time")).addOrder(OrderItem.asc("id"));
        } else {
            String sortOrder = query.getSortOrder();
            if (sortOrder.equals("ascending")) {
                page.addOrder(OrderItem.asc(StringConvertUtil.humpConversionUnderscore(query.getSortBy())));
            } else {
                page.addOrder(OrderItem.desc(StringConvertUtil.humpConversionUnderscore(query.getSortBy())));
            }
        }

        /**
         * SELECT
         * 	su.user_name,
         * 	(
         * 		SELECT
         * 			GROUP_CONCAT(sr.role_name)
         * 		FROM
         * 			sys_user_role sur,
         * 			sys_role sr
         * 		WHERE
         * 			sur.role_id = sr.id
         * 		AND sur.user_id = su.id
         * 	) roleName
         * FROM
         * 	sys_user su
         *
         * 执行结果：
         * --   user_name   role_name
         * --   admin       管理员
         * --   小明        班长,组员
         */

        // 查询 page 保证在参数列表的第一位，mp分页要用
        List<UserEntity> entityList = userMapper.getUserList(page, query);

        // 转换展示对象
        List<UserVo> voList = new ArrayList<>();
        for (UserEntity entity : entityList) {
            UserVo vo = new UserVo();
            BeanUtils.copyProperties(entity, vo);

            if (null != entity.getBirthday()) {
                vo.setBirthday(DateUtil.formatDateTime(entity.getBirthday()));
            }

            // 查询角色
            List<String> roles = userMapper.getUserRoleByUserId(entity.getId());
            String[] strings = new String[roles.size()];
            vo.setRoles(roles.toArray(strings));

            voList.add(vo);
        }
        // 返回 Page 对象
        Page<UserVo> result = new Page<>();
        BeanUtils.copyProperties(page, result);
        result.setRecords(voList);
        return result;
    }

    /**
     * 添加用户
     *
     * @param form
     */
    public void addUser(UserForm form) {
        // 校验用户名不为空
        if (StringUtils.isBlank(form.getUserName())) {
            throw new IllegalArgumentException("用户名不能为空");
        }

        // 对象数据转换
        UserEntity entity = new UserEntity();
        BeanUtils.copyProperties(form, entity);

        entity.preInsert();
        entity.setId(IdUtils.generateId());

        // 添加
        userMapper.insert(entity);
    }

    /**
     * 根据ID查询用户
     *
     * @param id
     */
    public UserVo getUserById(String id) {
        UserEntity entity = userMapper.selectById(id);
        if (null == entity) {
            return null;
        }
        UserVo vo = new UserVo();
        BeanUtils.copyProperties(entity, vo);
        if (null != entity.getBirthday()) {
            vo.setBirthday(DateUtil.formatDateTime(entity.getBirthday()));
        }
        vo.setRoles(new String[]{});
        return vo;
    }

    /**
     * 修改用户
     * 如果使用MP的update来更新数据，如果字段是null，则不会更新这个字段；
     * 解决方案：
     * ·加注解
     * ·手写update SQL
     * ·将该字段置成空字符串
     *
     * @param form
     */
    public void updateUser(UserForm form) {
        UserEntity entity = new UserEntity();
        BeanUtils.copyProperties(form, entity);
        entity.preUpdate();
        userMapper.updateById(entity);
    }

    /**
     * 根据用户ID删除用户
     *
     * @param id
     */
    public void delUserById(String id) {
        UserEntity entity = new UserEntity();
        entity.setId(id);
        entity.setStatus(DataStatus.OFF_LINE.getCode());
        userMapper.updateById(entity);
    }

    /**
     * 根据用户ID批量删除用户
     *
     * @param ids
     */
    public void delUserByIds(String[] ids) {
        Map<String, Object> map = new HashMap<>();
        map.put("ids", ids);
        map.put("updateBy", "1");
        map.put("updateTime", new Date());
        userMapper.delUserByIds(map);
    }

    /**
     * 根据用户名查询用户信息
     *
     * @param userName
     * @return
     */
    public UserEntity getUserByName(String userName) {
        QueryWrapper<UserEntity> qw = new QueryWrapper<>();
        qw.eq("status", DataStatus.ON_LINE.getCode());
        qw.eq("user_name", userName);
        return userMapper.selectOne(qw);
    }

    /**
     * 添加角色
     *
     * @param id    用户ID
     * @param roles 角色ID
     */
    public void addRole(String id, String[] roles) {
        // 删除角色
        userMapper.delRoleByUserId(id);

        // 保存角色
        List<UserRole> list = new ArrayList<>();
        for (String roleId : roles) {
            UserRole ur = new UserRole();
            ur.setId(IdUtils.generateId());
            ur.setUserId(id);
            ur.setRoleId(roleId);
            list.add(ur);
        }
        // 保存用户角色
        userMapper.addRole(list);
    }

    /**
     * 根据用户ID查询用户角色ID
     *
     * @param id
     * @return
     */
    public List<String> getUserRoleIdByUserId(String id) {
        return userMapper.getUserRoleIdByUserId(id);
    }

    /**
     * 根据用户名查询用户信息
     *
     * @param username
     * @return
     */
    public UserEntity loadUserByUsername(String username) {
        QueryWrapper<UserEntity> qw = new QueryWrapper<>();
        qw.eq("status", "50");
        qw.eq("user_name", username);
        qw.or();
        qw.eq("user_phone", username);
        qw.select("id", "user_name", "password", "user_img", "user_phone");
        return userMapper.selectOne(qw);
    }

    /**
     * 根据用户ID查询用户权限集合
     * @param id
     * @return
     */
    public List<String> getMenusByUserId(String id) {
        return userMapper.getMenusByUserId(id);
    }
}
